<template>
  <div class="performance-report">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>业绩报表</span>
          <div class="header-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              @change="handleDateChange"
            />
            <el-button type="primary" @click="exportReport" size="small">导出报表</el-button>
          </div>
        </div>
      </template>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stat-cards">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">总销售额</div>
              <div class="stat-value">¥{{ statistics.totalSales }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">订单数量</div>
              <div class="stat-value">{{ statistics.totalOrders }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">热销商品</div>
              <div class="stat-value">{{ statistics.hotProduct }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">平均客单价</div>
              <div class="stat-value">¥{{ statistics.avgOrderValue }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>热销商品排行（销售次数）</span>
            </template>
            <div ref="productChart" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>销售额趋势</span>
            </template>
            <div ref="salesChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细数据表格 -->
      <el-card class="detail-card">
        <template #header>
          <span>商品销售详情</span>
        </template>
        <el-table :data="productSalesData" style="width: 100%" v-loading="loading">
          <el-table-column prop="rank" label="排名" width="80" />
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="category" label="商品类别" width="120" />
          <el-table-column prop="brand" label="品牌" width="120" />
          <el-table-column prop="salesCount" label="销售次数" width="100" sortable />
          <el-table-column prop="salesAmount" label="销售金额" width="120" sortable>
            <template #default="{ row }">
              ¥{{ row.salesAmount }}
            </template>
          </el-table-column>
          <el-table-column prop="avgPrice" label="平均售价" width="100" />
          <el-table-column prop="stock" label="库存" width="80" />
          <el-table-column prop="stockWarning" label="库存预警" width="100">
            <template #default="{ row }">
              <el-tag :type="row.stockWarning ? 'danger' : 'success'">
                {{ row.stockWarning ? '库存不足' : '库存充足' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
        />
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

// 数据
const loading = ref(false)
const dateRange = ref([])
const productChart = ref(null)
const salesChart = ref(null)
let productChartInstance = null
let salesChartInstance = null

// 统计数据
const statistics = reactive({
  totalSales: '1,234,567',
  totalOrders: 1234,
  hotProduct: '运动鞋A1',
  avgOrderValue: '1,002'
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 商品销售数据
const productSalesData = ref([])

// 模拟数据
const mockProductSalesData = [
  {
    rank: 1,
    productName: '运动鞋A1',
    category: '运动鞋',
    brand: 'Nike',
    salesCount: 156,
    salesAmount: '78,000',
    avgPrice: 500,
    stock: 45,
    stockWarning: false
  },
  {
    rank: 2,
    productName: '休闲鞋B2',
    category: '休闲鞋',
    brand: 'Adidas',
    salesCount: 134,
    salesAmount: '67,000',
    avgPrice: 500,
    stock: 23,
    stockWarning: true
  },
  {
    rank: 3,
    productName: '皮鞋C3',
    category: '皮鞋',
    brand: 'Clarks',
    salesCount: 98,
    salesAmount: '98,000',
    avgPrice: 1000,
    stock: 67,
    stockWarning: false
  },
  {
    rank: 4,
    productName: '凉鞋D4',
    category: '凉鞋',
    brand: 'Birkenstock',
    salesCount: 87,
    salesAmount: '43,500',
    avgPrice: 500,
    stock: 12,
    stockWarning: true
  },
  {
    rank: 5,
    productName: '靴子E5',
    category: '靴子',
    brand: 'Timberland',
    salesCount: 76,
    salesAmount: '91,200',
    avgPrice: 1200,
    stock: 34,
    stockWarning: false
  }
]

// 初始化商品销售图表
const initProductChart = () => {
  if (productChartInstance) {
    productChartInstance.dispose()
  }
  
  productChartInstance = echarts.init(productChart.value)
  const option = {
    title: {
      text: '销售次数统计',
      subtext: '最近30天',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['运动鞋A1', '休闲鞋B2', '皮鞋C3', '凉鞋D4', '靴子E5'],
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '销售次数'
    },
    series: [
      {
        name: '销售次数',
        type: 'bar',
        data: [156, 134, 98, 87, 76],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        }
      }
    ]
  }
  productChartInstance.setOption(option)
}

// 初始化销售额趋势图表
const initSalesChart = () => {
  if (salesChartInstance) {
    salesChartInstance.dispose()
  }
  
  salesChartInstance = echarts.init(salesChart.value)
  const option = {
    title: {
      text: '销售额趋势',
      subtext: '最近30天',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        return params[0].name + '<br/>' + '销售额: ¥' + params[0].value
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['第1周', '第2周', '第3周', '第4周']
    },
    yAxis: {
      type: 'value',
      name: '销售额（元）'
    },
    series: [
      {
        name: '销售额',
        type: 'line',
        smooth: true,
        data: [320000, 332000, 301000, 334000],
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(128, 255, 165, 0.5)' },
            { offset: 1, color: 'rgba(1, 191, 236, 0.1)' }
          ])
        },
        lineStyle: {
          color: '#5470c6',
          width: 2
        },
        itemStyle: {
          color: '#5470c6'
        }
      }
    ]
  }
  salesChartInstance.setOption(option)
}

// 方法
const getReportData = () => {
  loading.value = true
  setTimeout(() => {
    productSalesData.value = mockProductSalesData
    total.value = mockProductSalesData.length
    loading.value = false
  }, 500)
}

const handleDateChange = () => {
  getReportData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const exportReport = () => {
  ElMessage.success('报表导出成功')
}

// 响应式处理
const handleResize = () => {
  if (productChartInstance) {
    productChartInstance.resize()
  }
  if (salesChartInstance) {
    salesChartInstance.resize()
  }
}

// 生命周期
onMounted(() => {
  getReportData()
  setTimeout(() => {
    initProductChart()
    initSalesChart()
  }, 100)
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (productChartInstance) {
    productChartInstance.dispose()
  }
  if (salesChartInstance) {
    salesChartInstance.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.performance-report {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 20px 0;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart-container {
  width: 100%;
  height: 320px;
}

.detail-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>